package fileHandling;

import java.util.HashMap;

import com.jme.image.Texture;
import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.scene.TriMesh;
import com.jme.scene.state.RenderState.StateType;
import com.jme.scene.state.TextureState;

public class ClonedModel {
	
	private CloneImportExport clone;
	private HashMap<String, Texture> textures;
	private Node orginal;
	
	public ClonedModel(Node model) {
		orginal = model;
		
		clone = new CloneImportExport();
		clone.saveClone(model);
		
		textures = new HashMap<String, Texture>();
		saveTextures(model);
	}
	
	private void saveTextures(Node parent) {
		if(parent.getChildren() == null) return;
		
		for(Spatial child : parent.getChildren()) {
			if(child instanceof Node) saveTextures((Node)child);
			else {
				assert(child instanceof TriMesh);
				TriMesh mesh = (TriMesh)child;
				TextureState ts = (TextureState)mesh.getRenderState(StateType.Texture);
				if(ts != null) textures.put(mesh.getName(), ts.getTexture());
			}
		}
	}
	
	public Node loadClone() {
		Node newNode = (Node)clone.loadClone();
		
		putTextures(newNode);
		
		return newNode;
	}
	
	private void putTextures(Node parent) {
		if(parent.getChildren() == null) return;
		
		for(Spatial child : parent.getChildren()) {
			if(child instanceof Node) putTextures((Node)child);
			else {
				assert(child instanceof TriMesh);
				TriMesh mesh = (TriMesh)child;
				TextureState ts = (TextureState)mesh.getRenderState(StateType.Texture);
				if(ts != null) ts.setTexture(textures.get(mesh.getName()), 0);
			}
		}
	}
	
	public void cleanParent() {
		orginal.removeFromParent();
	}
}